<template>
  <div style="display: flex; flex-direction: column; width: 100%;">
    <div style="display: flex; flex-direction: row; width: 100%">
      <div v-if="[1, 2].includes(userInfoStore.info?.roleId)">
        <el-button type="primary" style="width: 13vh;height: 3vh;" @click="dialogVisible=true">增加用户</el-button>
      </div>
      <!-- 	<div style="width: 3vh;"></div>
        <div v-if="[1, 2].includes(userInfoStore.info?.roleId)">
          <el-button type="primary" style="width: 13vh;height: 5vh;" @click="DeleteUser">删除用户</el-button>
        </div> -->
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="nickname" label="用户名"/>
      <el-table-column prop="username" label="用户名称"/>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="userId" label="钉钉id"/>
      <el-table-column prop="role" label="角色">
        <template #default="{ row }">
          <el-select v-model="row.roleId" placeholder="请选择" @change="handleSystemChange(row)">
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>

<!--      <el-table-column prop="imgUrl" label="头像">-->
<!--        <template #default="{ row }">-->
<!--          <el-upload-->
<!--              ref="uploadRef"-->
<!--              class="avatar-uploader"-->
<!--              :show-file-list="false"-->
<!--              :auto-upload="false"-->
<!--              :action="`/api/user/upload?userId=${row.id}`"-->
<!--              name="file"-->
<!--              :headers="{'Authorization': `Bearer ${tokenStore.token}`}"-->
<!--              :on-success="uploadSuccess(row)"-->
<!--              :on-change="handleAvatarChange"-->
<!--              :before-upload="beforeAvatarUpload"-->
<!--          >-->
<!--            <img v-if="row.imgUrl" :src="row.imgUrl" class="avatar"/>-->
<!--            <img v-else :src="defaultAvatar" class="avatar"/>-->
<!--          </el-upload>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="操作" width="400">
        <template #default="{ row }">
          <el-button type="primary" @click="handleSubmit(row)">提交</el-button>
          <el-button type="warning" @click="handleResetPassword(row.id)">重置密码</el-button>
          <el-button type="info" @click="handleEdit(row)">修改信息</el-button>
        </template>
      </el-table-column>
      <el-table-column label="删除">
        <template #default="{ row }">
          <el-button type="danger" :icon="Delete" circle @click="deleteUser(row.id)"/>
        </template>
      </el-table-column>

    </el-table>
  </div>
  <!-- 新增用户时出现的弹窗 -->
  <el-dialog v-model="dialogVisible" title="添加用户" width="30%">
    <!--更正bug-->
    <el-form :model="addUserData" :rules="rules" label-width="100px" :data="addUserData">
      <el-form-item label="账号" prop="username">
        <el-input v-model="addUserData.username" minlength="1"
                  maxlength="16" placeholder="请输入账号"></el-input>
      </el-form-item>
      <!--已修正bug-->
      <el-form-item label="用户名称" prop="nickname">
        <el-input v-model="addUserData.nickname" minlength="1" maxlength="15"
                  placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model.number="addUserData.phone" minlength="1" maxlength="11"
                  placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="钉钉id" prop="userId">
        <el-input v-model="addUserData.userId" minlength="1" maxlength="11"
                  placeholder="请输入您的钉钉id"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addUserData.password" minlength="1" maxlength="16"
                  placeholder="请设置密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="再次输入密码" prop="rePassword">
        <el-input v-model="addUserData.rePassword" minlength="1" maxlength="16"
                  placeholder="请设置密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="管理员角色" prop="role">
        <el-radio-group v-model="addUserData.roleId">
          <el-radio :label="1">超级管理员</el-radio>
          <el-radio :label="2">项目经理</el-radio>
          <el-radio :label="3">等保主管</el-radio>
          <el-radio :label="4">渗透主管</el-radio>
          <el-radio :label="5">渗透人员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改用户信息的弹窗 -->
  <el-dialog v-model="editDialogVisible" title="修改用户信息" width="30%">
    <el-form :model="editUserData" :rules="editRules" label-width="100px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="editUserData.username" minlength="1"
                  maxlength="16" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="用户名称" prop="nickname">
        <el-input v-model="editUserData.nickname" minlength="1" maxlength="15"
                  placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model.number="editUserData.phone" minlength="1" maxlength="11"
                  placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="钉钉id" prop="userId">
        <el-input v-model="editUserData.userId" minlength="1" maxlength="11"
                  placeholder="请输入钉钉id"></el-input>
      </el-form-item>
      <!-- <el-form-item label="管理员角色" prop="role">
        <el-radio-group v-model="editUserData.roleId">
          <el-radio :label="1">超级管理员</el-radio>
          <el-radio :label="2">项目经理</el-radio>
          <el-radio :label="3">等保主管</el-radio>
          <el-radio :label="4">渗透主管</el-radio>
          <el-radio :label="5">渗透人员</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useTokenStore} from "@/stores/token.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {
  addUserService,
  delectUserService,
  getRoleListService,
  getUserListService,
  uploadAvatarService,
  userAvatarUpdateService,
  resetUserPasswordService,
  editUserService
} from "@/api/user.js";
import {Delete, Edit} from "@element-plus/icons-vue";
import axios, {AxiosHeaders as Buffer} from "axios";

const tableData = ref([]);
const roleList = ref([]);
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const defaultAvatar = "@/avatar.jpg"; // 替换为默认头像路径

const getRoleList = async () => {
  try {
    const result = await getRoleListService();
    roleList.value = result.data;
  } catch (error) {
    ElMessage.error('加载角色列表失败');
  }
};

const getUserList = async () => {
  try {
    const result = await getUserListService();
    tableData.value = result.data;
    // 初始化时，将 null 的 role 设置为对应的 roleId
    tableData.value.forEach(row => {
      if (row.roleId && !row.role) {
        const role = roleList.value.find(item => item.id === row.roleId);
        if (role) {
          row.role = role.roleName;
        }
      }
    });
  } catch (error) {
    ElMessage.error('加载用户列表失败');
  }
};

const uploadSuccess = (row) => (response) => {
  if (response && response.message) {
    row.imgUrl = response.message;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error('上传失败');
  }
};

const handleAvatarChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    file.url = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("上传的文件必须是图片");
  }
  return isImage;
};

const handleSystemChange = (row) => {
  ElMessage.info('角色已更改');
};

const handleSubmit = async (row) => {
  try {
    const result = await userAvatarUpdateService(row.userId, row.roleId);
    if (result && result.message) {
      ElMessage.success(result.message);
    } else {
      ElMessage.success("提交成功，若页面未变动请刷新页面");
    }
  } catch (error) {
    ElMessage.error("提交失败");
  }
};

onMounted(() => {
  getRoleList();
  getUserList();
});

// 删除用户
const deleteUser = async (id) => {
  try {
    await ElMessageBox.confirm('点击确定删除', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await delectUserService(id);
    ElMessage.success('删除成功');
    await getUserList();
  } catch (error) {
    ElMessage.info('取消删除');
  }
}

// 修正bug，缺少model
const addUserData = ref({
  username: '',
  nickname: '',
  password: '',
  rePassword: '',
  phone: '',
  userId: '',
  roleId: ''
})
const dialogVisible = ref(false)

// const crypto = require('crypto');

const addUser = async () => {

  dialogVisible.value = true;
  // 修正bug，内容数据缺省，更正密码确认逻辑
  let addData = addUserData.value
  if (addData.password !== addData.rePassword) {
    ElMessage.error('两次输入的密码不一致');
    return;
  }
  if (addData.password === null) {
    ElMessage.error('密码不能为空');
    return;
  }
  let result = await addUserService(addData)
  if (result) {
    ElMessage.success('添加成功');
    await getUserList();
    dialogVisible.value = false;
  } else {
    ElMessage.error('添加失败');
  }

}

const handleResetPassword = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const result = await resetUserPasswordService(userId);
    ElMessage.success('密码重置成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败');
    }
  }
};

const rules = computed(() => ({
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {max: 16, message: '账号长度不能超过16个字符', trigger: 'blur'}
  ],
  nickname: [{required: true, message: '请输入用户名称', trigger: 'blur'}],
  phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  rePassword: [{required: true, message: '请再次输入密码', trigger: 'blur'}],
  userId: [{required: false, message: '请输入钉钉id', trigger: 'blur'}],
  role: [{required: true, message: '请选择管理员角色', trigger: 'blur'}]
}));

// 修改用户信息相关
const editDialogVisible = ref(false);
const editUserData = ref({
  id: '',
  username: '',
  nickname: '',
  phone: '',
  userId: '',
  roleId: ''
});

// 打开编辑对话框
const handleEdit = (row) => {
  editUserData.value = {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    phone: row.phone,
    userId: row.userId,
    roleId: row.roleId
  };
  editDialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  try {
    const result = await editUserService({
      id: editUserData.value.id,
      username: editUserData.value.username,
      nickname: editUserData.value.nickname,
      phone: editUserData.value.phone,
      userId: editUserData.value.userId,
      roleId: editUserData.value.roleId
    });
    
    if (result.code === 0) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      getUserList(); // 刷新用户列表
    } else {
      ElMessage.error(result.msg || '修改失败');
    }
  } catch (error) {
    console.error('修改用户信息错误:', error);
    ElMessage.error('修改失败');
  }
};

// 编辑表单的验证规则
const editRules = computed(() => ({
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {max: 16, message: '账号长度不能超过16个字符', trigger: 'blur'}
  ],
  nickname: [
    {required: true, message: '请输入用户名称', trigger: 'blur'},
    {max: 15, message: '用户名称长度不能超过15个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  userId: [
    {required: true, message: '请输入钉钉id', trigger: 'blur'}
  ]
}));

</script>

<style scoped>

.avatar-uploader {
  width: 50px;
  height: 50px;
  padding: 0;
  margin: 0;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}
</style>
